package org.jdamico.socks.server.commons;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class NetworkUtils {

		/**
		 * 鑾峰彇鏈湴IP鍒楄〃锛堥拡瀵瑰缃戝崱鎯呭喌锛�
		 * @return
		 */
		public static synchronized Map<String, Object> getLocalInetIdent() {

			Map<String, Object> ipMacInfo = null;
			try {
				Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
						.getNetworkInterfaces();
				while (networkInterfaces.hasMoreElements()) {
					NetworkInterface networkInterface = networkInterfaces
							.nextElement();
					Enumeration<InetAddress> inetAddresses = networkInterface
							.getInetAddresses();

					while (inetAddresses.hasMoreElements()) {
						InetAddress inetAddress = inetAddresses.nextElement();
						ipMacInfo = pickInetAddress(inetAddress, networkInterface);
						if (ipMacInfo != null) {
							return ipMacInfo;
						}
					}
				}
			} catch (SocketException e) {
				e.printStackTrace();
			}
			return null;
		}

		private static Map<String, Object> pickInetAddress(InetAddress inetAddress, NetworkInterface ni) {
			try {
				String name = ni.getDisplayName();
				if (name.contains("Adapter")
						|| name.contains("Virtual") || name.contains("VMnet") || name.contains("#")) {
					return null;
				}
				if (ni.isVirtual() || !ni.isUp() || !ni.supportsMulticast()) {
					return null;
				}
				if (inetAddress.isSiteLocalAddress()) {
					Formatter formatter = new Formatter();
					String sMAC = null;
					byte[] macBuf = ni.getHardwareAddress();
					for (int i = 0; i < macBuf.length; i++) {
						sMAC = formatter.format(Locale.getDefault(), "%02X%s",
								macBuf[i], (i < macBuf.length - 1) ? "-" : "")
								.toString();
					}
					formatter.close();
					Map<String, Object> ipMacInfo = new HashMap<String, Object>();
					ipMacInfo.put("hostname", inetAddress.getHostName()); //绯荤粺褰撳墠hostname
					ipMacInfo.put("ip", inetAddress.getHostAddress()); //ip鍦板潃
					ipMacInfo.put("ip_type", inetAddressTypeName(inetAddress)); //缃戠粶绫诲瀷
					ipMacInfo.put("os", System.getProperty("os.name")); //绯荤粺鍚嶇О
					ipMacInfo.put("mac", sMAC); //mac 鍦板潃
					ipMacInfo.put("cpu_arch", System.getProperty("os.arch")); //cpu鏋舵瀯
					ipMacInfo.put("network_device", ni.getDisplayName()); //缃戝崱鍚嶇О
					return ipMacInfo;
				}

			} catch (SocketException e) {
				e.printStackTrace();
			} 
			return null;
		}

		
		private static String inetAddressTypeName(InetAddress inetAddress) {
			return (inetAddress instanceof Inet4Address) ? "ipv4" : "ipv6";
		}

		
}
